# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(ggplot2)
library(data.table)
library(optparse)
library(ropls)
library(magrittr)
library(tibble)
library(tidyverse)

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
make_option("--mc", default = "meta_color.txt", type = "character", help = "metabolite color file")
)
opt <- parse_args(OptionParser(option_list = option_list))


sampleInfo <- read_csv(opt$g) %>%
    select(c("SampleID", "ClassNote"))

data <- read_csv(opt$i) %>%
select(- c("HMDB", "KEGG", "Metabolite"))

df <- data %>%
    group_by(Class) %>%
    summarise_all(sum) %>%
    mutate_at(vars(- "Class"), function(x){x * 100 / sum(x)}) %>%
    gather("SampleID", "Value", - Class)

sampleColDf <- read.csv(opt$sc, header = T, stringsAsFactors = F, comment.char = "") %>%
select(c("ClassNote", "col"))

sampleInfo

sortSamplesDf <- sampleInfo %>%
    left_join(sampleColDf, by = c("ClassNote")) %>%
    mutate(ClassNote = factor(ClassNote, levels = unique(sampleInfo$ClassNote))) %>%
    arrange(ClassNote) %>%
    mutate(Id = 1 : n())

sortSamplesDf

uniqClassNotes <- unique(sortSamplesDf$ClassNote)

print("===")
df <- df %>%
    inner_join(sortSamplesDf, by = c("SampleID")) %>%
    arrange(ClassNote)

metaColDf <- read_tsv(opt$mc) %>%
select(c("Class", "col"))
metaCols <- metaColDf %>%
deframe()

width<-10+max(0,nrow(sampleInfo)-20)*0.1

pdf("Class_Barplot_by_Sample.pdf", width = width, height = 7)

pdf <- df

pdf

yPos <- 104
pOffset <- 0.5
annoYPos <- 107
yBreaks <- seq(0, 100, by = 25)

sortSamples <- unique(pdf$SampleID)
sortSamples

p <- ggplot(pdf, mapping = aes(x = Id, y = Value, fill = Class)) +
    xlab("") +
    ylab("Relative Abundance(%)") +
    theme_classic(base_size = 8.8, base_family = "Times") +
    theme(axis.text.x = element_text(angle = 90, size = 8, hjust = 1, vjust = 0.5), panel.grid.minor = element_blank(),
    axis.text.y = element_text(size = 15), legend.position = 'bottom', panel.grid.major = element_blank(),
    panel.border = element_blank(), axis.title.y = element_text(size = 15),
    legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'), axis.ticks = element_line(colour = "black", size = 0.5),
    legend.text = element_text(size = 8), axis.title.x = element_text(size = 11), legend.key.size = unit(1, "line"),
    axis.line = element_blank(), plot.margin = unit(c(0.5, 0.5, 0.5, 0.5), "cm")
    ) +
    geom_col() +
    scale_fill_manual("", values = metaCols) +
    scale_x_continuous("", labels = sortSamplesDf$SampleID, breaks = sortSamplesDf$Id, expand = c(0, 0)) +
    scale_y_continuous(breaks = yBreaks)


for (v in uniqClassNotes) {
    df <- sortSamplesDf %>%
    filter(ClassNote == v)
    id <- df$Id
    x = id[1]
    xend = id[length(id)]
    col <- unique(df$col)
    p <- p + geom_segment(aes_string(x = (x - pOffset), xend = (xend + pOffset), y = yPos, yend = yPos), colour = col,
    linetype = "solid", size = 3)
    p <- p + annotate("text", x = median(id) , y = annoYPos, label = v, hjust = 1, size = 5, family = "Times")
}
p

dev.off()
